<script setup lang="ts">
import { reactive, ref } from 'vue';
import { useMessage } from 'naive-ui';
import { fetchGetConfigList, fetchUpdateConfig } from '@/service/api/system/config';

defineOptions({
  name: 'WechatConfig'
});

const message = useMessage();

// 微信配置表单
interface WechatConfig {
  appid: string;
  secret: string;
  enabled: boolean;
  redirectUri: string;
}

const wechatConfig = reactive<WechatConfig>({
  appid: '',
  secret: '',
  enabled: false,
  redirectUri: ''
});

const loading = ref(false);
const saving = ref(false);

// 加载微信配置
async function loadWechatConfig() {
  loading.value = true;
  try {
    // 获取所有配置项
    const { data } = await fetchGetConfigList({
      pageNum: 1,
      pageSize: 100,
      configKey: 'wechat.mp'
    });

    if (data && data.rows) {
      data.rows.forEach((config: any) => {
        switch (config.configKey) {
          case 'wechat.mp.appid':
            wechatConfig.appid = config.configValue || '';
            break;
          case 'wechat.mp.secret':
            wechatConfig.secret = config.configValue || '';
            break;
          case 'wechat.mp.enabled':
            wechatConfig.enabled = config.configValue === 'true';
            break;
          case 'wechat.mp.redirect_uri':
            wechatConfig.redirectUri = config.configValue || '';
            break;
          default:
            // 其他配置项不处理
            break;
        }
      });
    }
  } catch (error) {
    message.error('加载微信配置失败');
    // eslint-disable-next-line no-console
    console.error('加载微信配置失败:', error);
  } finally {
    loading.value = false;
  }
}

// 保存微信配置
async function saveWechatConfig() {
  saving.value = true;
  try {
    // 获取现有配置项的ID
    const { data } = await fetchGetConfigList({
      pageNum: 1,
      pageSize: 100,
      configKey: 'wechat.mp'
    });

    const configMap = new Map();
    if (data && data.rows) {
      data.rows.forEach((config: any) => {
        configMap.set(config.configKey, config.configId);
      });
    }

    // 更新各个配置项
    const updatePromises = [];

    // 更新AppID
    if (configMap.has('wechat.mp.appid')) {
      updatePromises.push(
        fetchUpdateConfig({
          configId: configMap.get('wechat.mp.appid'),
          configKey: 'wechat.mp.appid',
          configValue: wechatConfig.appid,
          configName: '微信小程序AppID',
          configType: 'N',
          remark: '微信小程序的AppID，用于小程序登录认证'
        })
      );
    }

    // 更新AppSecret
    if (configMap.has('wechat.mp.secret')) {
      updatePromises.push(
        fetchUpdateConfig({
          configId: configMap.get('wechat.mp.secret'),
          configKey: 'wechat.mp.secret',
          configValue: wechatConfig.secret,
          configName: '微信小程序AppSecret',
          configType: 'N',
          remark: '微信小程序的AppSecret，用于小程序登录认证'
        })
      );
    }

    // 更新启用状态
    if (configMap.has('wechat.mp.enabled')) {
      updatePromises.push(
        fetchUpdateConfig({
          configId: configMap.get('wechat.mp.enabled'),
          configKey: 'wechat.mp.enabled',
          configValue: wechatConfig.enabled ? 'true' : 'false',
          configName: '微信小程序登录开关',
          configType: 'N',
          remark: '是否启用微信小程序登录功能 (true/false)'
        })
      );
    }

    // 更新回调地址
    if (configMap.has('wechat.mp.redirect_uri')) {
      updatePromises.push(
        fetchUpdateConfig({
          configId: configMap.get('wechat.mp.redirect_uri'),
          configKey: 'wechat.mp.redirect_uri',
          configValue: wechatConfig.redirectUri,
          configName: '微信小程序回调地址',
          configType: 'N',
          remark: '微信小程序登录的回调地址'
        })
      );
    }

    await Promise.all(updatePromises);
    message.success('微信配置保存成功');
  } catch (error) {
    message.error('保存微信配置失败');
    // eslint-disable-next-line no-console
    console.error('保存微信配置失败:', error);
  } finally {
    saving.value = false;
  }
}

// 测试配置
function testConfig() {
  if (!wechatConfig.appid || !wechatConfig.secret) {
    message.warning('请先填写AppID和AppSecret');
    return;
  }
  message.info('配置测试功能开发中');
}

// 页面加载时获取配置
loadWechatConfig();
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden">
    <NCard title="微信小程序配置" :bordered="false" class="card-wrapper">
      <NSpin :show="loading">
        <NForm :model="wechatConfig" :show-require-mark="false" label-width="120px" label-placement="left">
          <NGrid :cols="24" :x-gap="18">
            <NGi :span="24">
              <NFormItem label="启用小程序登录" path="enabled">
                <NSwitch v-model:value="wechatConfig.enabled">
                  <template #checked>启用</template>
                  <template #unchecked>禁用</template>
                </NSwitch>
              </NFormItem>
            </NGi>

            <NGi :span="24">
              <NFormItem label="AppID" path="appid" required>
                <NInput v-model:value="wechatConfig.appid" placeholder="请输入微信小程序AppID" />
              </NFormItem>
            </NGi>

            <NGi :span="24">
              <NFormItem label="AppSecret" path="secret" required>
                <NInput
                  v-model:value="wechatConfig.secret"
                  type="password"
                  show-password-on="mousedown"
                  placeholder="请输入微信小程序AppSecret"
                />
              </NFormItem>
            </NGi>

            <NGi :span="24">
              <NFormItem label="回调地址" path="redirectUri">
                <NInput
                  v-model:value="wechatConfig.redirectUri"
                  placeholder="https://your-domain.com/auth/social/callback?source=wechat_mp"
                />
              </NFormItem>
            </NGi>

            <NGi :span="24">
              <div class="flex gap-12px">
                <NButton type="primary" :loading="saving" @click="saveWechatConfig">保存配置</NButton>
                <NButton @click="testConfig">测试配置</NButton>
                <NButton @click="loadWechatConfig">重新加载</NButton>
              </div>
            </NGi>
          </NGrid>
        </NForm>
      </NSpin>
    </NCard>

    <NCard title="配置说明" :bordered="false" class="card-wrapper">
      <NSpace vertical>
        <div>
          <strong>1. 获取AppID和AppSecret：</strong>
          <p>登录微信公众平台 (mp.weixin.qq.com)，在"开发" -> "开发管理" -> "开发设置"中获取</p>
        </div>
        <div>
          <strong>2. 配置服务器域名：</strong>
          <p>在微信公众平台的"开发" -> "开发管理" -> "开发设置" -> "服务器域名"中配置request合法域名</p>
        </div>
        <div>
          <strong>3. 回调地址说明：</strong>
          <p>回调地址应该是您的后端服务地址，格式为：https://your-domain.com/auth/social/callback?source=wechat_mp</p>
        </div>
        <div>
          <strong>4. 安全提醒：</strong>
          <p class="text-red-500">AppSecret是敏感信息，请妥善保管，不要泄露给第三方</p>
        </div>
      </NSpace>
    </NCard>
  </div>
</template>

<style scoped></style>
